package com.hexinfo.dmpro.monitor.service.serviceparam;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.hexinfo.dmpro.common.base.BaseService;
import com.hexinfo.dmpro.common.base.Page;
import com.hexinfo.dmpro.common.base.PageResult;
import com.hexinfo.dmpro.common.utils.StringUtils;
import com.hexinfo.dmpro.monitor.config.MonitorCache;
import com.hexinfo.dmpro.monitor.dao.CmSwitchDao;
import com.hexinfo.dmpro.monitor.dao.MonitorDao;
import com.hexinfo.dmpro.monitor.dao.serviceparam.CmTargetParamDao;
import com.hexinfo.dmpro.monitor.model.base.MonitorReq;
import com.hexinfo.dmpro.monitor.model.serviceparam.*;
import com.hexinfo.dmpro.monitor.service.CmStateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CmTargetParamService extends BaseService {

    @Autowired
    private CmTargetParamDao cmTargetParamDao;
    @Autowired
    private GiveAnAlarmService giveAnAlarmService;
    @Autowired
    private DingDingAlarmService dingDingAlarmService;
    @Autowired
    private CmStateService cmStateService;
    @Autowired
    private MonitorDao monitorDao;
    @Autowired
    private CmSwitchDao cmSwitchDao;
    @Autowired
    private MonitorCache monitorCache;
    @Autowired
    private CmTargetParamHandlerService cmTargetParamHandlerService;

    @Value("${warn.jumpUrl}")
    private String jumpUrl;
    @Value("${warn.isAtAll}")
    private String isAtAll;
    @Value("${warn.source}")
    private String source;
    @Value("${warn.cmEverydayInspect}")
    private String cmEverydayInspect;
    @Value("${warn.cmServiceWarn}")
    private String cmServiceWarn;

    /**
     * 指标参数首页查询
     *
     * @param page
     * @param req
     * @return
     */
    public PageResult selClusterService(Page page, CmServiceParamReq req) {
        return selectPage(cmTargetParamDao, "selClusterService", page, req);
    }

    /**
     * 参数管理-关键指标-组件栏
     * @param req
     * @return
     */
    public List<String> selClusterServiceType(CmServiceParamReq req) {
        return cmTargetParamDao.selClusterServiceType(req);
    }

    /**
     * 指标告警首页查询
     *
     * @param page
     * @param req
     * @return
     */
    public PageResult selTargetAlarmInfo(Page page, CmServiceParamReq req) {
        return selectPage(cmTargetParamDao, "selTargetAlarmInfo", page, req);
    }

    /**
     * 集群指标配置信息保存
     * @param req
     * @return
     */
    public int saveClusterServiceTarget(CmServiceParamReq req){
        //先删除
        cmTargetParamDao.delClusterTarget(req);
        int i = 0;
        if(CollectionUtil.isNotEmpty(req.getCmTargetList())){
            //再新增
            i = cmTargetParamDao.insClusterTarget(req);
        }
        return i;
    }

    /**
     * 集群指标配置信息查询
     * @param req
     * @return
     */
    public List<CmTargetServiceModel> selClusterServiceTarget(CmServiceParamReq req){
        List<CmTargetServiceModel> cmTargetServiceModels = cmTargetParamDao.selClusterServiceTarget(req);
        List<CmTargetServiceModel> cmTargetServiceModelsOther = cmTargetParamDao.selClusterServiceTargetOther(req);
        cmTargetServiceModels.addAll(cmTargetServiceModelsOther);
        return cmTargetServiceModels;
    }

    /**
     * 按指标编码获取指标数据
     * @return
     */
    public CmTargetServiceModel queryTargetCode(String targetCode){
        return cmTargetParamDao.queryTargetCode(targetCode);
    }


    /**
     * 告警信息处理保存
     * @param req
     * @return
     */
    public int upTargetAlarmInfo(CmServiceParamReq req){
        return cmTargetParamDao.upTargetAlarmInfo(req);
    }

    /**
     * 查询量参数配置信息
     * @param req
     * @return
     */
    public PageResult selMonitorTargetConfig(Page page, CmServiceParamReq req) {
        return selectPage(cmTargetParamDao, "selMonitorTargetConfig", page, req);
    }

    /**
     * 容量参数配置信息保存
     * @param req
     * @return
     */
    public int insMonitorTargetConfig(CmServiceParamReq req){
        //新增
        return cmTargetParamDao.insMonitorTargetConfig(req);
    }

    /**
     * 容量参数配置信息删除
     * @param req
     * @return
     */
    public int delMonitorTargetConfig(CmServiceParamReq req){
        int i = cmTargetParamDao.delMonitorTargetConfig(req);
        //删除容量参数配置同时删除告警发送
        WarnSendConfigModel warn = cmTargetParamDao.selWarnSendConfigName(req.getId());
        if(warn != null && warn.getId() != null){
            deleteWarnSendConfig(warn.getId());
        }
        return i;
    }

    /**
     * 容量参数配置信息修改
     * @param req
     * @return
     */
    public int upMonitorTargetConfig(CmServiceParamReq req){
        return cmTargetParamDao.upMonitorTargetConfig(req);
    }

    /**
     * 查询指标明细信息 前端图形  获取集群某个服务下所有指标编码
     * @param req
     * @return
     */
    public List<Map<String,List<CmReportModel>>> selTargetDetailList(CmServiceParamReq req) {
        List<CmTargetModel> cmTargetModelList = cmTargetParamDao.selTargetAlarmValueList(req);
        List<Map<String,List<CmReportModel>>> mapList = new ArrayList<>();
        for (CmTargetModel cmTargetModel : cmTargetModelList) {

            if (cmTargetModel == null || StringUtils.isBlank(cmTargetModel.getAlarmValue())) {
                List<CmReportModel> list = new ArrayList<>();
                Map<String,List<CmReportModel>> map = new HashMap<String,List<CmReportModel>>();
                map.put(cmTargetModel.getTargetCode(), list);
                mapList.add(map);
                continue;
            }
            req.setAlarmValue(cmTargetModel.getAlarmValue());
            //添加指标编码，来获取每个指标编码对应的实体集合
            req.setTargetCode(cmTargetModel.getTargetCode());
            String time = "";
            //判断时间区间  1小时 6小时 12小时 1天(24小时) 3天(72小时) 7天(168小时)，获取当前时间前的日期时间
            if (StringUtils.isNotBlank(req.getHourSum())) {
                switch (req.getHourSum()) {
                    case "1":
                        time = LocalDateTime.now().minusMinutes(60).toString().replace("T", " ");
                        req.setCreateTime(time);
                        break;
                    case "6":
                        time = LocalDateTime.now().minusHours(6).toString().replace("T", " ");
                        req.setCreateTime(time);
                        break;
                    case "12":
                        time = LocalDateTime.now().minusHours(12).toString().replace("T", " ");
                        req.setCreateTime(time);
                        break;
                    case "24":
                        time = LocalDateTime.now().minusDays(1).toString().replace("T", " ");
                        req.setCreateTime(time);
                        break;
                    case "72":
                        time = LocalDateTime.now().minusDays(3).toString().replace("T", " ");
                        req.setCreateTime(time);
                        break;
                    case "168":
                        time = LocalDateTime.now().minusWeeks(1).toString().replace("T", " ");
                        req.setCreateTime(time);
                        break;
                    default:

                }
            }
            List<CmReportModel> list = new ArrayList<>();
            List<CmTargetReportModel> returnList = new LinkedList();
            List<Integer> intList = new ArrayList<>();
            long betweenDay = 0L;
            if (StringUtils.isNotBlank(req.getHourStartTime()) && StringUtils.isNotBlank(req.getHourEndTime())) {
                Date date1 = DateUtil.parse(req.getHourStartTime());
                Date date2 = DateUtil.parse(req.getHourEndTime());
                //获取小时时间差
                betweenDay = DateUtil.between(date1, date2, DateUnit.HOUR);
            }
            //大于一天 查询小时表  查询区间大于24小时 查询小时表
            if ((StringUtils.isNotBlank(req.getHourSum()) && Integer.parseInt(req.getHourSum()) > 24)
                    || (StringUtils.isNotBlank(req.getHourStartTime()) && StringUtils.isNotBlank(req.getHourEndTime()) && betweenDay > 24)
            ) {
                list = cmTargetParamDao.selTargetDetail(req);
            } else {
                list = cmTargetParamDao.selTargetDetail(req);
            }
            //指标个数为2时，大小字节B转MB
            if ("2".equals(cmTargetModel.getTargetNum())){
                for (CmReportModel cmReportModel : list) {
                    List<CmTargetReportModel> modellist = cmReportModel.getCmTargetReportModellist();
                    for (int i = 0; i<modellist.size();i++) {
                        String format = String.format("%.2f", Double.parseDouble(modellist.get(i).getTargetValue()) / (1024 * 1024));
                        modellist.get(i).setTargetValue(format);
                    }
                }
            }
            List<CmReportModel> cmReportModels = new ArrayList<>();
            int i = 0;
            //防止指标名称改名后，出现同名的多个队列，统一用最新的指标名称
            for (CmReportModel a : list) {
                a.setTargetName(cmTargetModel.getTargetName());
                list.set(i,a);
                i = i + 1;
            }
            //去除未选中的任务
            if (null != req.getEntityNames()) {
                for (CmReportModel a : list) {
                    if (req.getEntityNames().contains(a.getEntityName())) {
                        cmReportModels.add(a);
                    }
                }
                Map<String,List<CmReportModel>> map = new HashMap<String,List<CmReportModel>>();
                map.put(cmTargetModel.getTargetCode(), cmReportModels);
                mapList.add(map);
                continue;
            }
            Map<String,List<CmReportModel>> map = new HashMap<String,List<CmReportModel>>();
            //去除空的图表
           if (list.size() > 0){
               map.put(cmTargetModel.getTargetCode(), list);
               mapList.add(map);
           }
        }
        return mapList;
    }

    /**
     * 查询指标明细信息 前端图形  获取集群某个服务下所有实体名称
     * @param req
     * @return
     */
    public List<Map<String,List<String>>> getTopNameList(CmServiceParamReq req) {
        List<Map<String,List<CmReportModel>>> cmReportModelLists = this.selTargetDetailList(req);
        //获取多个指标编码的实体名称list
        List<Map<String,List<String>>> mapList = new ArrayList<>();
        for (Map<String, List<CmReportModel>> cmReportModelMap : cmReportModelLists) {
            Set<Map.Entry<String,List<CmReportModel>>> entries = cmReportModelMap.entrySet();
            for (Map.Entry<String,List<CmReportModel>> entry : entries) {
                List<CmTargetReportModel> sort = new ArrayList<>();
                //获取所有实体任务中TargetValue最大的实体任务进行排序
                for (CmReportModel cm : entry.getValue()) {
                    List<CmTargetReportModel> cmTargetReportModellist = cm.getCmTargetReportModellist();
                    //获取num列表取最大值，排序，获取最大值
                    cmTargetReportModellist.sort((x,y)->Float.compare(Float.parseFloat(y.getTargetValue()),Float.parseFloat(x.getTargetValue())));
                    CmTargetReportModel cmTargetReportModel = cmTargetReportModellist.get(0);
                    cmTargetReportModel.setPro(cm.getEntityName());
                    sort.add(cmTargetReportModel);
                }
                sort.sort((x,y)->Float.compare(Float.parseFloat(y.getTargetValue()),Float.parseFloat(x.getTargetValue())));
                List<String> topName = sort.stream()
                        .map(CmTargetReportModel::getPro).collect(Collectors.toList());
                Map<String,List<String>> map = new HashMap<String,List<String>>();
                map.put(entry.getKey(), topName);
                mapList.add(map);
            }
        }
        return mapList;
    }

    public List<CmReportModel> selTargetDetail(CmServiceParamReq req) {
        CmTargetModel cmTargetModel = cmTargetParamDao.selTargetAlarmValue(req);
        if (cmTargetModel == null || StringUtils.isBlank(cmTargetModel.getAlarmValue())) {
            List<CmReportModel> list = new ArrayList<>();
            return list;
        }
        req.setAlarmValue(cmTargetModel.getAlarmValue());
        String time = "";
        //判断时间区间  1小时 6小时 12小时 1天(24小时) 3天(72小时) 7天(168小时)，获取当前时间前的日期时间
        if (StringUtils.isNotBlank(req.getHourSum())) {
            switch (req.getHourSum()) {
                case "1":
                    time = LocalDateTime.now().minusMinutes(60).toString().replace("T", " ");
                    req.setCreateTime(time);
                    break;
                case "6":
                    time = LocalDateTime.now().minusHours(6).toString().replace("T", " ");
                    req.setCreateTime(time);
                    break;
                case "12":
                    time = LocalDateTime.now().minusHours(12).toString().replace("T", " ");
                    req.setCreateTime(time);
                    break;
                case "24":
                    time = LocalDateTime.now().minusDays(1).toString().replace("T", " ");
                    req.setCreateTime(time);
                    break;
                case "72":
                    time = LocalDateTime.now().minusDays(3).toString().replace("T", " ");
                    req.setCreateTime(time);
                    break;
                case "168":
                    time = LocalDateTime.now().minusWeeks(1).toString().replace("T", " ");
                    req.setCreateTime(time);
                    break;
                default:

            }
        }
        List<CmReportModel> list = new ArrayList<>();
        List<CmTargetReportModel> returnList = new LinkedList();
        List<Integer> intList = new ArrayList<>();
        long betweenDay = 0L;
        if (StringUtils.isNotBlank(req.getHourStartTime()) && StringUtils.isNotBlank(req.getHourEndTime())) {
            Date date1 = DateUtil.parse(req.getHourStartTime());
            Date date2 = DateUtil.parse(req.getHourEndTime());
            //获取小时时间差
            betweenDay = DateUtil.between(date1, date2, DateUnit.HOUR);
        }
        //大于一天 查询小时表  查询区间大于24小时 查询小时表
        if ((StringUtils.isNotBlank(req.getHourSum()) && Integer.parseInt(req.getHourSum()) > 24)
                || (StringUtils.isNotBlank(req.getHourStartTime()) && StringUtils.isNotBlank(req.getHourEndTime()) && betweenDay > 24)
        ) {
            list = cmTargetParamDao.selTargetDetail(req);
        } else {
            list = cmTargetParamDao.selTargetDetail(req);
        }

        //指标个数为2时，大小字节B转MB
        if ("2".equals(cmTargetModel.getTargetNum())){
            for (CmReportModel cmReportModel : list) {
                List<CmTargetReportModel> modellist = cmReportModel.getCmTargetReportModellist();
                for (int i = 0; i<modellist.size();i++) {
                    String format = String.format("%.2f", Double.parseDouble(modellist.get(i).getTargetValue()) / (1024 * 1024));
                    modellist.get(i).setTargetValue(format);
                }
            }
        }
        List<CmReportModel> cmReportModels = new ArrayList<>();
        //防止指标名称改名后，出现同名的多个队列，统一用最新的指标名称
        int i = 0;
        for (CmReportModel a : list) {
            a.setTargetName(cmTargetModel.getTargetName());
            list.set(i,a);
            i = i + 1;
        }
        //去除未选中的任务
        if (null != req.getEntityNames() && req.getEntityNames().size()>0) {
            for (CmReportModel a : list) {
                if (req.getEntityNames().contains(a.getEntityName())) {
                    cmReportModels.add(a);
                }
            }
            return cmReportModels;
        }
        return list;
    }

    public List<String> getTopName(CmServiceParamReq req) {
        List<CmReportModel> cmReportModels = this.selTargetDetail(req);
        List<CmTargetReportModel> sort = new ArrayList<>();
        //获取所有实体任务中TargetValue最大的实体任务进行排序
        for (CmReportModel cm : cmReportModels) {
            List<CmTargetReportModel> cmTargetReportModellist = cm.getCmTargetReportModellist();
            //获取num列表取最大值，排序，获取最大值
            cmTargetReportModellist.sort((x,y)->Float.compare(Float.parseFloat(y.getTargetValue()),Float.parseFloat(x.getTargetValue())));
            CmTargetReportModel cmTargetReportModel = cmTargetReportModellist.get(0);
            cmTargetReportModel.setPro(cm.getEntityName());
            sort.add(cmTargetReportModel);
        }
        sort.sort((x,y)->Float.compare(Float.parseFloat(y.getTargetValue()),Float.parseFloat(x.getTargetValue())));
        List<String> topName = sort.stream()
                .map(CmTargetReportModel::getPro).collect(Collectors.toList());
        return topName;
    }

    /**
     * 获取容量参数设置服务类型
     * @return
     */
    public List<String> selServiceType() {
        return cmTargetParamDao.selServiceType();
    }

    /**
     * 按服务类型查询容量参数设置
     * @return
     */
    public List<CmTargetServiceModel> selTypeTargetConfig(String serviceType) {
        return cmTargetParamDao.selTypeTargetConfig(serviceType);
    }

    /**
     * 按指标名称查询告警用户信息
     * @return
     */
    public List<WarnSendConfigModel> selTypeWarningUser(String targetName) {
        return cmTargetParamDao.selTypeWarningUser(targetName);
    }

    /**
     * 按指标名称、集群编码，查询告警用户信息
     * @return
     */
    public List<WarnSendConfigModel> selTypeAndFlagWarningUser(String targetName,String cmFlag,String clusterFlag) {
        return cmTargetParamDao.selTypeAndFlagWarningUser(targetName,cmFlag,clusterFlag);
    }

    /**
     * 获取接收人-列表
     * @return
     */
    public PageResult selWarningUserList(Page page,WarningUserModel user) {
        return selectPage(cmTargetParamDao, "selWarningUser", page,user);
    }

    /**
     * 获取接收人
     * @return
     */
    public List<WarningUserModel> selWarningUser() {
        return cmTargetParamDao.selWarningUser();
    }

    /**
     * 添加接收人
     * @return
     */
    public int addWarningUser(WarningUserModel warn) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        warn.setId(uuid);
        return cmTargetParamDao.addWarningUser(warn);
    }

    /**
     * 修改接收人
     * @return
     */
    public int updateWarningUser(WarningUserModel warn) {
        return cmTargetParamDao.updateWarningUser(warn);
    }

    /**
     * 删除接收人
     * @return
     */
    public int deleteWarningUser(String id) {
        return cmTargetParamDao.deleteWarningUser(id);
    }

    /**
     * 参数管理-告警详情-告警发送-添加
     * @return
     */
    public Boolean addWarnSendConfig(WarnSendConfigModel warn) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        warn.setId(uuid);
        if (cmTargetParamDao.addWarnSendConfig(warn) == 1){
            if (warn.getWarningUserModels() != null && warn.getWarningUserModels().size() > 0){
                if (cmTargetParamDao.addWarningNoUser(warn) >= 0){
                    return true;
                }
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 参数管理-告警详情-告警发送-修改
     * @return
     */
    public Boolean updateWarnSendConfig(WarnSendConfigModel warn) {
        if (cmTargetParamDao.updateWarnSendConfig(warn) == 1){
            if (cmTargetParamDao.deleteWarningNoUser(warn.getId()) >= 0){
                if (cmTargetParamDao.addWarningNoUser(warn) >= 0){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 参数管理-告警详情-告警发送-删除
     * @return
     */
    public Boolean deleteWarnSendConfig(String id) {
        if (cmTargetParamDao.deleteWarnSendConfig(id) >= 0){
            if (cmTargetParamDao.deleteWarningNoUser(id) >= 0){
                return true;
            }
        }
        return false;
    }

    /**
     * 参数管理-告警详情-告警发送-列表
     *
     * @param page
     * @param warn
     * @return
     */
    public PageResult selWarnSendConfig(Page page, WarnSendConfigModel warn) {
        PageResult selWarnSendConfig = null;
        if(warn == null || warn.getRecipientName() == null || warn.getRecipientName().isEmpty()){
            selWarnSendConfig = selectPage(cmTargetParamDao, "selWarnSendConfig", page, warn);

        }else {
            selWarnSendConfig = selectPage(cmTargetParamDao, "selUserWarnSendConfig", page, warn);
        }
        List<WarnSendConfigModel> content = (List<WarnSendConfigModel>) selWarnSendConfig.getContent();
        for (WarnSendConfigModel warnSendConfigModel : content) {
            warnSendConfigModel.setWarningUserModels(cmTargetParamDao.selWarnUserdId(warnSendConfigModel.getId()));
        }
        selWarnSendConfig.setContent(content);
        return selWarnSendConfig;
    }

    /**
     * 参数管理-告警详情-告警发送-发布
     * @return
     */
    public int releaseWarnSendConfig(String id) {
        return cmTargetParamDao.releaseWarnSendConfig(id);
    }

    /**
     * 参数管理-告警详情-告警发送-待发布
     * @return
     */
    public int noReleaseWarnSendConfig(String id) {
        return cmTargetParamDao.noReleaseWarnSendConfig(id);
    }

    /**
     * 微信、钉钉告警，然后添加进告警日志表
     * @return
     */
    public void warnWxDingDingAndLog(String cmFlag,String cmName,String clusterFlag,String clusterName,String serviceName,
                               String warnAlert,String publishTheme) {
        warnAlert = "["+DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss")+"]" +"\n"+warnAlert;
        //获取告警用户
        List<WarnSendConfigModel> warns = selTypeAndFlagWarningUser(publishTheme,cmFlag,clusterFlag);
        CmTargetServiceModel model = queryTargetCode(publishTheme);
        String targetName = "";
        if (model != null && StrUtil.isNotBlank(model.getTargetName())){
            targetName = model.getTargetName();
        }
        List<WarnSendLogModel> WarnSendLogModel = new ArrayList<>();
        if (warns != null){
            for (WarnSendConfigModel warn : warns) {
                List<String> names = new ArrayList<>();
                List<String> phones = new ArrayList<>();
                if (StringUtils.isNotBlank(warn.getRecipientName())){
                    names = Arrays.asList(warn.getRecipientName().split(","));
                }
                if (StringUtils.isNotBlank(warn.getRecipientPhone())){
                    phones = Arrays.asList(warn.getRecipientPhone().split(","));
                }
                if ("1".equals(warn.getSendingType())){
                    //微信
                    WXGiveAnAlarmModel wx = new WXGiveAnAlarmModel(source,cmFlag,clusterFlag,names,warnAlert,jumpUrl);
                    String b = giveAnAlarmService.giveAnAlarmWX(wx);
                    String uuid = UUID.randomUUID().toString().replace("-", "");
                    WarnSendLogModel warnLog = new WarnSendLogModel(uuid,cmFlag,cmName,clusterFlag,clusterName,serviceName,
                            targetName,warn.getRecipientUserName(),warnAlert,"1",b);
                    WarnSendLogModel.add(warnLog);
                }else if ("2".equals(warn.getSendingType())){
                    //钉钉
                    String b = dingDingAlarmService.dingDingAlarm(warnAlert,phones,isAtAll);
                    String uuid = UUID.randomUUID().toString().replace("-", "");
                    WarnSendLogModel warnLog = new WarnSendLogModel(uuid,cmFlag,cmName,clusterFlag,clusterName,serviceName,
                            targetName,warn.getRecipientUserName(),warnAlert,"2",b);
                    WarnSendLogModel.add(warnLog);
                }else {
                    //微信
                    WXGiveAnAlarmModel wx = new WXGiveAnAlarmModel(source,cmFlag,clusterFlag,names,warnAlert,jumpUrl);
                    String s = giveAnAlarmService.giveAnAlarmWX(wx);
                    String uuids = UUID.randomUUID().toString().replace("-", "");
                    WarnSendLogModel warnLogs = new WarnSendLogModel(uuids,cmFlag,cmName,clusterFlag,clusterName,serviceName,
                            targetName,warn.getRecipientUserName(),warnAlert,"1",s);
                    WarnSendLogModel.add(warnLogs);
                    //钉钉
                    String b = dingDingAlarmService.dingDingAlarm(warnAlert,phones,isAtAll);
                    String uuid = UUID.randomUUID().toString().replace("-", "");
                    WarnSendLogModel warnLog = new WarnSendLogModel(uuid,cmFlag,cmName,clusterFlag,clusterName,serviceName,
                            targetName,warn.getRecipientUserName(),warnAlert,"2",b);
                    WarnSendLogModel.add(warnLog);
                }
            }
        }
        if (WarnSendLogModel.size()>0){
            //添加进告警日志表
            cmTargetParamDao.addWarnLog(WarnSendLogModel);
        }
    }

    /**
     * 微信、钉钉告警，然后添加进告警日志表
     * (告警发送管理打开就发送)
     * @return
     */
    public void warnWxDingDingAndLog1(String cmFlag,String cmName,String clusterFlag,String clusterName,String serviceName,
                                     String warnAlert,String publishTheme) {
        warnAlert = "["+DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss")+"]" +"\n"+warnAlert;
        //获取告警用户
        List<WarnSendConfigModel> warns = selTypeWarningUser(publishTheme);
        CmTargetServiceModel model = queryTargetCode(publishTheme);
        String targetName = "";
        if (model != null && StrUtil.isNotBlank(model.getTargetName())){
            targetName = model.getTargetName();
        }
        List<WarnSendLogModel> WarnSendLogModel = new ArrayList<>();
        if (warns != null){
            for (WarnSendConfigModel warn : warns) {
                List<String> names = new ArrayList<>();
                List<String> phones = new ArrayList<>();
                if (StringUtils.isNotBlank(warn.getRecipientName())){
                    names = Arrays.asList(warn.getRecipientName().split(","));
                }
                if (StringUtils.isNotBlank(warn.getRecipientPhone())){
                    phones = Arrays.asList(warn.getRecipientPhone().split(","));
                }
                if ("1".equals(warn.getSendingType())){
                    //微信
                    WXGiveAnAlarmModel wx = new WXGiveAnAlarmModel(source,cmFlag,clusterFlag,names,warnAlert,jumpUrl);
                    String b = giveAnAlarmService.giveAnAlarmWX(wx);
                    String uuid = UUID.randomUUID().toString().replace("-", "");
                    WarnSendLogModel warnLog = new WarnSendLogModel(uuid,cmFlag,cmName,clusterFlag,clusterName,serviceName,
                            targetName,warn.getRecipientUserName(),warnAlert,"1",b);
                    WarnSendLogModel.add(warnLog);
                }else if ("2".equals(warn.getSendingType())){
                    //钉钉
                    String b = dingDingAlarmService.dingDingAlarm(warnAlert,phones,isAtAll);
                    String uuid = UUID.randomUUID().toString().replace("-", "");
                    WarnSendLogModel warnLog = new WarnSendLogModel(uuid,cmFlag,cmName,clusterFlag,clusterName,serviceName,
                            targetName,warn.getRecipientUserName(),warnAlert,"2",b);
                    WarnSendLogModel.add(warnLog);
                }else {
                    //微信
                    WXGiveAnAlarmModel wx = new WXGiveAnAlarmModel(source,cmFlag,clusterFlag,names,warnAlert,jumpUrl);
                    String s = giveAnAlarmService.giveAnAlarmWX(wx);
                    String uuids = UUID.randomUUID().toString().replace("-", "");
                    WarnSendLogModel warnLogs = new WarnSendLogModel(uuids,cmFlag,cmName,clusterFlag,clusterName,serviceName,
                            targetName,warn.getRecipientUserName(),warnAlert,"1",s);
                    WarnSendLogModel.add(warnLogs);
                    //钉钉
                    String b = dingDingAlarmService.dingDingAlarm(warnAlert,phones,isAtAll);
                    String uuid = UUID.randomUUID().toString().replace("-", "");
                    WarnSendLogModel warnLog = new WarnSendLogModel(uuid,cmFlag,cmName,clusterFlag,clusterName,serviceName,
                            targetName,warn.getRecipientUserName(),warnAlert,"2",b);
                    WarnSendLogModel.add(warnLog);
                }
            }
        }
        if (WarnSendLogModel.size()>0){
            //添加进告警日志表
            cmTargetParamDao.addWarnLog(WarnSendLogModel);
        }
    }

    /**
     * 告警日志表分页
     *
     * @param page
     * @param warn
     * @return
     */
    public PageResult selWarnSendLog(Page page, WarnSendLogModel warn) {
        return selectPage(cmTargetParamDao, "selWarnSendLog", page, warn);
    }

    /**
     * 日常巡检
     *
     * @return
     */
    public String seleveryDayInspect() {
        List<MonitorReq> cmNameInfoList = monitorCache.getCms("1");
        Map<String, MonitorReq> cmNameInfoMap = cmNameInfoList.stream().collect(Collectors.toMap(MonitorReq::getCmName, monitorReq -> monitorReq));
        //1.获取CM服务监控
        Map<String, String> serviceStrMap = cmTargetParamHandlerService.getCmServiceStrMap(cmNameInfoMap);
        //2.zookeeper连接数监控:44个链接
        Map<String, String> zookeeperStrMap = cmTargetParamHandlerService.getZookeeperStrMap(cmNameInfoMap);
        //3.impala每个主机监控:每个主机jvm近30分最大
        Map<String, String> impalaStrMap = cmTargetParamHandlerService.getImpalaStrMap(cmNameInfoMap);
        //4.HDFS使用容量/总容量
        Map<String, Map<String, String>> hdfsStrMap = cmTargetParamHandlerService.getHdfsStrMap(cmNameInfoMap);
        //5.hive的连接数
        Map<String, String> hiveConnsStrMap = cmTargetParamHandlerService.getHiveConnsStrMap(cmNameInfoMap);
        //6.impala的连接数
        Map<String, String> impalaConnsStrMap = cmTargetParamHandlerService.getImpalaConnsStrMap(cmNameInfoMap);
        //7.Hive metastore JVM使用状态
        Map<String, String> hiveMetastoreStrMap = cmTargetParamHandlerService.getHiveMetastoreStrMap(cmNameInfoMap);
        //8.Hive server2 JVM使用状态
        Map<String, String> hiveServer2StrMap = cmTargetParamHandlerService.getHiveServer2StrMap(cmNameInfoMap);
        //9.HBase RegionServer GC回收时间峰值
        Map<String, String> hbaseRegionServerStrMap = cmTargetParamHandlerService.getHbaseRegionServerStrMap(cmNameInfoMap);
        //10.HBase Master JVM使用状态
        Map<String, String> hbaseMasterJvmStrMap = cmTargetParamHandlerService.getHbaseMasterJvmStrMap(cmNameInfoMap);
        //11.HBase RegionServer JVM使用状态
        Map<String, String> hbaseRegionServerJvmStrMap = cmTargetParamHandlerService.getHbaseRegionServerJvmStrMap(cmNameInfoMap);
        //12.Zookeeper JVM使用状态
        Map<String, String> zookeeperJvmStrMap = cmTargetParamHandlerService.getZookeeperJvmStrMap(cmNameInfoMap);
        //13.主机状态
        Map<String, String> hostsHealthSummaryStrMap = cmTargetParamHandlerService.getHostsHealthSummaryStrMap(cmNameInfoMap);
        //14.万国集群监控大屏 impala和yarn失败任务监控
        Map<String, String> impalaYarnStrFailStrMap = cmTargetParamHandlerService.getImpalaYarnStrFailStrMap(cmNameInfoMap);
        //15.hdfs丢失块监控
        Map<String, String> hdfsLossBlockStrMap = cmTargetParamHandlerService.getHdfsLossBlockStrMap(cmNameInfoMap);
        // 遍历集群发送巡检信息
        for (String cmName : cmNameInfoMap.keySet()) {
            String warnMessage = "";
            if (StrUtil.equals(cmNameInfoMap.get(cmName).getSortId(), "1")) {
                // 拼Impala的
                warnMessage = "【" + cmName + "】impala 巡检：\n" +
                        "(1) CM服务监控：\n" + serviceStrMap.get(cmName) +
                        "(2) 最近30分钟zookeeper连接数监控：" + zookeeperStrMap.get(cmName) +
                        "(3) 最近30分钟Impala连接数监控：" + impalaConnsStrMap.get(cmName) +
                        "(4) 最近30分钟Impala Daemon JVM 峰值：" + impalaStrMap.get(cmName) +
                        "(5) HDFS容量监控：" + hdfsStrMap.get(cmName).get("useValue") + "，占比：" + hdfsStrMap.get(cmName).get("proportion") + "%，丢失块监控：" + hdfsLossBlockStrMap.get(cmName) +
                        "(6) Hive状态健康，最近30分钟metastore JVM峰值：" + hiveMetastoreStrMap.get(cmName) + ", server2 JVM峰值：" + hiveServer2StrMap.get(cmName) +
                        "(7) 主机状态：" + hostsHealthSummaryStrMap.get(cmName) + "\n" +
                        "(8) " + cmName + "监控大屏： \n" + impalaYarnStrFailStrMap.get(cmName);
            } else if (StrUtil.equals(cmNameInfoMap.get(cmName).getSortId(), "2")) {
                // 拼HBase的
                warnMessage = "【" + cmName + "】HBase 巡检：\n" +
                        "(1) CM服务监控：\n" + serviceStrMap.get(cmName) +
                        "(2) 最近30分钟，zookeeper连接数监控：" + zookeeperStrMap.get(cmName) +
                        "(3) HDFS 容量监控：" + hdfsStrMap.get(cmName).get("useValue") + "，占比：" + hdfsStrMap.get(cmName).get("proportion") + "%，丢失块监控：" + hdfsLossBlockStrMap.get(cmName) +
                        "(4) 最近30分钟HBase RegionServer GC回收时间峰值：" + hbaseRegionServerStrMap.get(cmName) +
                        "(5) 最近30分钟HBase Master/RegionServer JVM heapsize 峰值：" + hbaseMasterJvmStrMap.get(cmName) + ", " + hbaseRegionServerJvmStrMap.get(cmName) +
                        "(6) Zookeeper JVM堆栈监控：" + zookeeperJvmStrMap.get(cmName);
            }
            MonitorReq monitorReq = cmNameInfoMap.get(cmName);
            //发送日常巡检，钉钉
            warnWxDingDingAndLog(monitorReq.getCmFlag(), monitorReq.getCmName(), monitorReq.getClusterFlag(), monitorReq.getClusterName(), "所有服务",warnMessage,cmEverydayInspect);
        }
        return "日常巡检-发送成功";
    }

    /**
     * cm服务监控
     *
     * @return
     */
    public String cmServiceWarn() {
        //1.获取CM服务监控
        String serviceStr = cmStateService.serviceError();
        if ("".equals(serviceStr)){
            return "CM服务监控-服务无异常";
        }
        String warnAlert = "CM服务实时监控：\n"+serviceStr;
        //发送日常巡检，钉钉
//        warnWxDingDingAndLog("cmFlag","所有集群","clusterFlag","所有子集群","所有服务",warnAlert,cmServiceWarn);
        return "CM服务监控-发送成功";
    }
}
